package com.huishi.ui;


import com.huishi.entity.*;
import com.huishi.entity.vo.UploadMsgVO;
import com.huishi.handler.execute.PlacingFilesService;
import com.huishi.handler.ws.WebSocketServer;
import com.huishi.mapper.*;
import com.huishi.ui.server.FileChooserUIServer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 文件落盘小程序
 */
@Data
@Component
@Slf4j
public class FileChooserUI extends JFrame {

    @Autowired
    private PlacingFilesService placingFilesService;
    @Autowired
    private ScheduledExecutorService scheduler;

    @Autowired
    private PlacingFileTaskMapper placingFileTaskMapper;

    // 查询字典======
    @Autowired
    private DictTargetMapper dictTargetMapper;
    @Autowired
    private DictPwdFormatMapper dictPwdFormatMapper;
    @Autowired
    private DictGatherMapper dictGatherMapper;
    @Autowired
    private DictSystemModelMapper dictSystemModelMapper;

    // 字典 start====
    // 数据来源
    private JComboBox<DictDataSource> dataSourceComboBox;
    // 目标对象
    private JComboBox<DictTarget> targetObjectComboBox;
    // pdw格式
    private JComboBox<DictPwdFormat> pdwComboBox;
    // 采集地点
    private JComboBox<DictGather> gatherPlaceComboBox;
    // 系统型号
    private JComboBox<DictSystemModel> systemModelComboBox;

    public JTextField processLogField;// 用户名称，操作人文本框
    // 字典 end======

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private WebSocketClient webSocketClient;


    public JTextField folderPathField; // 选择目录文本框
    public JTextField taskNameField; // 任务名称文本框

    public JTextField userNameField;// 用户名称，操作人文本框

    public JLabel fileNumLabel;
    public Integer fileNums;// 文件数

    public JLabel fileTotalSizeLabel;
    public Double fileTotalSize;// 文件总大小

    private JLabel speedLabel;
    public Double speed;// 速率

    private JLabel takeTimeLabel;
    public Long takeTime;// 用时

    public JLabel leftTimeLabel;
    public Double leftTime;// 剩余时间

    private Long unFinishedTaskId;// 未完成任务id

    private UploadMsgVO uploadMsg;// 上传任务信息

    // 落盘进度条
    public JProgressBar progressBar;

    int width = 800;
    int height = 260;
    JPanel comBox5 = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));// 自定义字段容器
    Map<Integer, JTextField> customColumnVs = new HashMap<>(); // 自定义字段

    @Autowired
    private FileChooserUIServer fileChooserServer;
//    @Autowired
//    private FunctionSelectionUI functionSelectionUI;

    private JButton sendButton;

    // 定时器：监控文件上传进度等数据 通过ws连接发送给后台汇总
    private Timer sendUploadMsgTimer = new Timer(1000, e -> fileChooserServer.processUploadMsg(this));


    @PreDestroy
    public void beforeDestroy() {
        fileChooserServer.recordUnFinishTask(this);
    }

    public FileChooserUI() {
        ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "\\upload.png");
        setIconImage(icon.getImage());
    }

    @PostConstruct
    public void init() {
        // 在构造器执行后进行初始化工作，包括依赖注入
//        initUI();
        scheduler.submit(this::initUI);
    }

    private void initUI() {
        setTitle("海量电磁数据自动迁移工具");
        setSize(width, height);
        // 窗口的关闭操作：点击窗口的关闭按钮时，程序会退出。这是通过 JFrame.EXIT_ON_CLOSE 实现的。
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        addWindowListener(new WindowAdapter() {
//            @Override
//            public void windowClosing(WindowEvent e) {
//                functionSelectionUI.setVisible(true);
//            }
//        });
        setLocationRelativeTo(null);// 将窗口居中显示

        // 禁用窗口缩放和拖拽调整大小
        setResizable(false);

        // 初始化文本框
        folderPathField = new JTextField();
        folderPathField.setEditable(false);
        folderPathField.setColumns(18);

        taskNameField = new JTextField(18);
        taskNameField.setEditable(true);

        userNameField = new JTextField(9);
        processLogField = new JTextField(9);

        // 初始化进度条
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true); // 显示百分比
        progressBar.setPreferredSize(new Dimension(300, 20)); // 设置进度条的大小

        // 填充下拉框的值
        fileChooserServer.fillComBoxValue(this);
        fileChooserServer.setComponent(this);


        JButton chooseButton = new JButton("选择文件或目录");
        // 给选择文件按钮添加事件:选完文件夹将绝对路径展示在folderPathField中
        chooseButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
//            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // 仅文件夹
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); // 支持文件和文件夹选择

            String folderPath = folderPathField.getText();
            File currentDirectory = new File(folderPath);
            if (currentDirectory.exists()) {
                fileChooser.setCurrentDirectory(currentDirectory); // 设置当前目录为 folderPathField 的目录
            }


            int result = fileChooser.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
//                File selectedFolder = fileChooser.getSelectedFile();
                File selectedFileOrFolder = fileChooser.getSelectedFile();
                folderPathField.setText(selectedFileOrFolder.getAbsolutePath());
            }
        });


        sendButton = new JButton("开始上传");
        sendButton.addActionListener(e -> fileChooserServer.startUpload(this));

        // 添加事件，如果有变化就更新上传任务名=====
        addEventToUpdateTaskName();

        // 设置布局为BorderLayout
        setLayout(new BorderLayout());

        // 创建垂直的Box容器
        Box vBox = Box.createVerticalBox();
        Box hBox1 = Box.createHorizontalBox();

        // 创建面板用于放置选择文件相关组件
        JPanel choosePanel = new JPanel();
        choosePanel.add(chooseButton);
        choosePanel.add(folderPathField);

        JPanel taskNamePanel = new JPanel();
        taskNamePanel.add(new JLabel("任务名称："));
        taskNamePanel.add(taskNameField);

        JPanel userNamePanel = new JPanel();
        taskNamePanel.add(new JLabel("操作人："));
        taskNamePanel.add(userNameField);


        hBox1.add(choosePanel);
        hBox1.add(taskNamePanel);
        hBox1.add(userNamePanel);


        // 2创建水平的Box容器 hBox2：目标对象、pdw格式、采集地点、系统型号
        Box hBox2 = Box.createHorizontalBox();
        // 创建面板用于放置数据来源下拉框
/*        JPanel dataSourceComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        dataSourceComBox.add(new JLabel("数据来源:"));
        dataSourceComBox.add(dataSourceComboBox);
        hBox2.add(dataSourceComBox);*/


        // 创建面板用于放置pdw格式下拉框
/*        JPanel pdwComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        pdwComBox.add(new JLabel("pdw格式:"));
        pdwComBox.add(pdwComboBox);
        hBox2.add(pdwComBox);*/

        // 系统型号下拉框
        JPanel comBox4 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        comBox4.add(new JLabel("系统型号:"));
        comBox4.add(systemModelComboBox);
        hBox2.add(comBox4);

        // 下拉框
        JPanel comBox3 = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        comBox3.add(new JLabel("采集地点:"));
        comBox3.add(gatherPlaceComboBox);
        hBox2.add(comBox3);

        // 创建面板用于放置目标对象下拉框
        JPanel targetComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        targetComBox.add(new JLabel("目标对象:"));
        targetComBox.add(targetObjectComboBox);
        hBox2.add(targetComBox);

        JPanel processLogComBox = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
        processLogComBox.add(new JLabel("处理记录:"));
        processLogComBox.add(processLogField);
        hBox2.add(processLogComBox);


        // 3创建水平的Box容器 hBox2_2：预留字段
        Box hBox2_2 = Box.createHorizontalBox();
//        JPanel comBox5 = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        comBox5.add(new JLabel("    "));
        JButton customColumnBtn = new JButton("自定义字段");
        comBox5.add(customColumnBtn);
        hBox2_2.add(comBox5);

        // 处理未完成的落盘文件任务
        fileChooserServer.processUnFinishedTask(this);

        AtomicInteger columnNum = new AtomicInteger(customColumnVs.size());
        customColumnBtn.addActionListener(e -> {
            if (columnNum.get() == 6) {
                JOptionPane.showMessageDialog(null, "最多自定义6个字段！", "提示", JOptionPane.INFORMATION_MESSAGE);
                return; // 最多自定义6个字段
            }

            JTextField jTextField = new JTextField(10);
            customColumnVs.put(columnNum.incrementAndGet(), jTextField);
            comBox5.add(new JLabel("  自定义字段" + columnNum.get() + ":"));
            comBox5.add(jTextField);

            // 换行处理
            if (columnNum.get() == 3) {
                comBox5.add(new JLabel("           " +
                        "                           "));
            }
            if (columnNum.get() % 4 == 0) setSize(width, height += 45);

            // 强制重新布局和绘制
            comBox5.revalidate();
            comBox5.repaint();

//            revalidate();
//            repaint();
        });
//        hBox2_2.add(comBox5);

        Box hBox2_3 = Box.createHorizontalBox();
        fileNumLabel = new JLabel();
        fileTotalSizeLabel = new JLabel();
        speedLabel = new JLabel();
        takeTimeLabel = new JLabel();
        leftTimeLabel = new JLabel();
        hBox2_3.add(fileNumLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(fileTotalSizeLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(speedLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(takeTimeLabel);
        hBox2_3.add(Box.createHorizontalStrut(20));
        hBox2_3.add(leftTimeLabel);

        // 进度条
        Box hBox3 = Box.createHorizontalBox();
        hBox3.add(progressBar);

        vBox.add(Box.createVerticalStrut(5));
        vBox.add(hBox1);
        vBox.add(hBox2);
        vBox.add(hBox2_2);
        vBox.add(hBox2_3);
        vBox.add(hBox3);

        // 将选择文件相关组件放在北部，开始落盘按钮放在南部
        add(vBox, BorderLayout.CENTER);

        JPanel sendPanel = new JPanel();
        sendPanel.add(sendButton);
        add(sendPanel, BorderLayout.SOUTH);

        setVisible(true);
        log.info("文件落盘UI创建成功");
    }

    /**
     * 添加事件，当有变化时就更新上传任务名
     */
    private void addEventToUpdateTaskName() {
        folderPathField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateTaskNameField();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateTaskNameField();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateTaskNameField();
            }
        });


        targetObjectComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        pdwComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        gatherPlaceComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
            }
        });

        systemModelComboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateTaskNameField();
                DictSystemModel systemModel = (DictSystemModel) systemModelComboBox.getSelectedItem();
                String msg = systemModel.getModel() + "，上传 " + systemModel.getDataFormat() + " 后缀的数据文件";
                JDialog dialog = new JOptionPane(msg, JOptionPane.INFORMATION_MESSAGE).createDialog("提示");
                dialog.setAlwaysOnTop(true);  // 设置置顶
                dialog.setVisible(true);      // 显示对话框
            }
        });
    }


    /**
     * 更新任务名称
     */
    private void updateTaskNameField() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // Check if all JComboBox instances have selections
        if (targetObjectComboBox.getSelectedItem() != null &&
//                pdwComboBox.getSelectedItem() != null &&
                gatherPlaceComboBox.getSelectedItem() != null &&
                systemModelComboBox.getSelectedItem() != null &&
                folderPathField.getText() != null) {

            String selectedValues =
                    sdf.format(new Date()) + "_" +
//                            folderPathField.getText().substring(folderPathField.getText().lastIndexOf("\\") + 1) + "_" +
                            systemModelComboBox.getSelectedItem().toString() + "_" +
                            gatherPlaceComboBox.getSelectedItem().toString() + "_" +
                            targetObjectComboBox.getSelectedItem().toString();
            taskNameField.setText(selectedValues);
        }
    }

//    public static void main(String[] args) {
////        SwingUtilities.invokeLater(() -> {
////            new FileChooserUI();
////        });
//        new FileChooserUI();
//    }

}


